<template>
  <div
    class="view-container"
    :style="{
      width: widget.width + 'px',
      height: widget.height + 'px',
    }"
  >
    <div class="view-content">
      <!-- <div id="SetQRCode" ref="qrCodeRef"></div> -->
      <img id="SetQRCode" ref="qrCodeRef" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { computed, watch } from 'vue'
  import { useEleStore } from '@/store/modules/coms'
  import JsBarcode from 'jsbarcode'
  const props = defineProps<{
    index: number
  }>()
  const Store = useEleStore()
  const widget = computed(() => {
    return Store.getWidgets[props.index]
  })
  const qrCodeRef = ref(null) as any
  const setQRCode = () => {
    JsBarcode(qrCodeRef.value, widget.value.content, {
      format: 'CODE128', //条形码的格式
      width: widget.value.codeWidth,
      height: widget.value.height,
      // height: 30,
      lineColor: widget.value.codeColor || '#000000',
      displayValue: false,
      margin: 1,
    })
  }
  watch(
    () => widget.value?.codeColor,
    () => {
      nextTick(() => {
        if (qrCodeRef.value) {
          while (qrCodeRef.value.firstChild) {
            qrCodeRef.value.removeChild(qrCodeRef.value.firstChild)
          }
          setQRCode()
        }
      })
    },
    { deep: true }
  )
  watch(
    () => [
      widget.value?.codeWidth,
      widget.value?.content,
      widget.value?.height,
    ],
    () => {
      nextTick(() => {
        // if (qrCodeRef.value) {
        //   while (qrCodeRef.value.firstChild) {
        //     qrCodeRef.value.removeChild(qrCodeRef.value.firstChild)
        //   }
        //   setQRCode()
        // }
        if (widget.value && qrCodeRef.value) {
          setQRCode()
        }
      })
    },
    { deep: true }
  )
  onMounted(() => {
    nextTick(() => {
      if (qrCodeRef.value) {
        setQRCode()
      }
    })
  })
</script>

<style lang="scss" scoped>
  .view-container {
    width: 100%;
    height: 100%;

    .view-content {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
    }
  }
  // ::v-deep #SetQRCode {
  //   height: 100%;
  //   width: 100%;
  // }
</style>
